<template>
  <div class="x-buttons flex-1">
    <button
      v-for="x in options"
      :key="x.id"
      class="x-button-item"
      :class="{ checked: isMultiple ? value.includes(x.value) : x.value === value, 'error': showError }"
      @click="handClick(x)"
    >
      {{ x.name }}
    </button>
  </div>
</template>

<script
  lang="ts"
  setup
  name="XButtons"
>

// eslint-disable-next-line vue/require-prop-types
const props = defineProps(['modelValue', 'options', 'multiple', 'error'])
const emit = defineEmits(['update:modelValue', 'change'])

const isMultiple = computed(() => {
  const { multiple } = props
  return multiple !== undefined && multiple !== false
})

const value = computed({
  get: () => props.modelValue,
  set: (v) => {
    emit('update:modelValue', v)
    emit('change', v)
  },
})

const handClick = (item) => {
  let v
  if (isMultiple.value) {
    const { modelValue } = props
    const oldItem = modelValue.find((n) => n === item.value)
    v = oldItem !== undefined ? modelValue.filter((n) => n !== item.value) : modelValue.concat(item.value)
  } else {
    v = item.value
  }
  value.value = v
}

const showError = computed(() => {
  if (value.value !== '') {
    return false;
  }
  if (props.error && value.value === '') {
    return true;
  }
  if (typeof props.error === 'boolean') {
    return props.error;
  }
});
</script>

<style
  scoped
  lang="scss"
>
.x-buttons {
  position: relative;
  z-index: 2;

  .x-button-item {
    @apply w-full;
    height: $form-item-height;
    background: $input-bg;
    border-radius: 6px;
    font-size: $form-font-size;
    line-height: $form-item-height;
    color: rgba(255, 255, 255, 1);
    border: 1px solid transparent;

    &+.x-button-item {
      margin-top: 12.5px;
    }

    &.checked {
      box-sizing: border-box;
      @include button-hover;
    }

    &:hover {
      box-sizing: border-box;
      @include button-hover;
    }
  }

  .error {
    box-shadow: $form-error;
  }
}
</style>
